package com.why.controller;

import com.why.pojo.Category;
import com.why.result.Result;
import com.why.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //新增文章分类
    @PostMapping("/add")
    public Result<Category> add(@RequestBody @Validated(Category.Add.class) Category category){
        log.info("***新增文章分类***");
        categoryService.add(category);
        Category byCategoryName = categoryService.getByCategoryName(category.getCategoryName());
        return Result.success(byCategoryName);
    }

    //根据分类名称查询分类信息
    @PostMapping("/getByCategoryName")
    public Result<Category> getByCategoryName(@RequestParam String categoryName){
        log.info("***根据分类名称查询分类信息***");
        Category category = categoryService.getByCategoryName(categoryName);
        return Result.success(category);
    }

    //查询文章分类列表
    @GetMapping("/list")
    public Result<List<Category>> listCategory(){
        log.info("***查询文章分类列表***");
        List<Category> categoryList = categoryService.listCategory();
        return Result.success(categoryList);
    }

    //根据ID获取文章分类详情
    @GetMapping("/detail")
    public Result<Category> detail(@RequestParam String id){
        log.info("***根据ID获取文章分类详情***");
        Category category = categoryService.detail(id);
        return Result.success(category);
    }

    //更新文章分类
    @PutMapping("/update")
    public Result<Category> updateCategory(@RequestBody @Validated(Category.Update.class) Category category){
        log.info("***更新文章分类***");
        categoryService.updateCategory(category);
        Category byCategoryName = categoryService.getByCategoryName(category.getCategoryName());
        return Result.success(byCategoryName);
    }

    //根据id删除文章分类
    @DeleteMapping("/delete")
    public Result<Integer> delete(@RequestParam Integer id){
        log.info("***根据id删除文章分类***");
        categoryService.removeById(id);
        return Result.success(id);
    }
}
